﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FullEmojiList
{
    public class HtmlHandle
    {
        public static void LoadHtml(string content)
        {
            string dic = Environment.CurrentDirectory + "/emoji";
            if (!Directory.Exists(dic))
                Directory.CreateDirectory(dic);
            HtmlDocument html = new HtmlDocument();
            html.LoadHtml(content);
            var tbodys = html.DocumentNode.SelectNodes("//tbody");
            if(tbodys.Count>0)
            {
                HtmlNode tbody = tbodys[0];
                int count = tbody.ChildNodes.Count;
                for (int i = 0; i < count; i++)
                {
                    HtmlNode tr = tbody.ChildNodes[i];
                    if (tr.ChildNodes.Count > 0)
                        ExportImage(tr);
                }
            }
            
        }

        static void ExportImage(HtmlNode tr)
        {
            var td = tr.ChildNodes[0];
            if (td.Name != "td")
            {
                return;
            }
            int uc = tr.ChildNodes.Count;
            string code = null;
            string imageData = null;
            for (int j = 1; j < uc; j++)
            {
                td = tr.ChildNodes[j];
                string tdType = td.GetAttributeValue("class", "rchars");
                switch (tdType)
                {
                    case "code":
                        code = td.FirstChild.InnerText;
                        break;
                    case "andr alt":
                        imageData = td.FirstChild.GetAttributeValue("src", null);
                        goto label;
                }
            }
            label:;
            if(code!=null && imageData!=null)
            {
                string path = Environment.CurrentDirectory + "/emoji/"+code+".png";
                TransImage(imageData,path);
            }
        }

        static void TransImage(string base64,string path)
        {
            base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
            byte[] bytes = Convert.FromBase64String(base64);
            MemoryStream memStream = new MemoryStream(bytes);
            Image mImage = Image.FromStream(memStream);
            Bitmap bp = new Bitmap(mImage);
            bp.Save(path, System.Drawing.Imaging.ImageFormat.Png);
            bp.Dispose();
            mImage.Dispose();
            memStream.Dispose();
        }
    }
}
